package com.corpdata.app.contract.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.corpdata.app.contract.dao.ContractReceivableMapper;
import com.corpdata.app.contract.entity.ContractInfo;
import com.corpdata.app.contract.entity.ContractReceivable;
import com.corpdata.app.contract.service.ContractReceivableService;
import com.corpdata.app.finance.entity.FinancialSetting;
import com.corpdata.app.finance.service.FinancialSettingService;
import com.corpdata.app.message.entity.SysMessage;
import com.corpdata.app.message.entity.SysMessageUser;
import com.corpdata.app.message.service.SysMessageService;
import com.corpdata.common.result.Result;
import com.corpdata.common.result.util.ResultUtil;
import com.corpdata.common.utils.CorpdataUtil;
import com.corpdata.common.utils.DateUtils;
import com.corpdata.core.base.AbstractBaseService;
import com.corpdata.system.security.shiro.util.UserUtil;

/**
 * 合同应收
 * 
 * @author wu
 * @email 64088839@qq.com
 * @date 2018-07-04 11:12:41
 */
@Service
@Transactional
public class ContractReceivableServiceImpl extends AbstractBaseService<ContractReceivable> implements ContractReceivableService {
	
	@Autowired
	ContractReceivableMapper contractReceivableMapper;
	
	@Autowired
	FinancialSettingService setServ;
	
	@Autowired
	SysMessageService msgServ;
	
	public Result insert(ContractReceivable receivable,String contractInfoId,String rent,int interest) throws Exception{
		Result result=null;
		//获取系统设置的缴租日
		FinancialSetting set = setServ.findByStatus("6");
		ContractInfo contractInfo=new ContractInfo();
		contractInfo.setId(contractInfoId);
		Calendar calendar = Calendar.getInstance();
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date startDate =receivable.getStartDate();//开始时间
		Date endDate =receivable.getEndDate();//结束时间
		String topDate=sdf.format(startDate);
		String bakeDate=sdf.format(startDate);
		BigDecimal monthRent = new BigDecimal(rent);//月租金
		double number=0;
		while (CorpdataUtil.compare_date(topDate, sdf.format(endDate))<0) {
			
			bakeDate=CorpdataUtil.addMonth(bakeDate,interest);
			number=interest;
			
			if(CorpdataUtil.compare_date(bakeDate, sdf.format(endDate))<0){
				ContractReceivable record=new ContractReceivable();
				//record.setReceivableNumber(CorpdataUtil.newGuid());
				record.setContract(contractInfo);
				record.setId(CorpdataUtil.getUUID());
				record.setCreater(UserUtil.getCurrentUserid());
				record.setCreated(date);
				record.setState(0);
				record.setModified(date);
				record.setMonthRent(monthRent);
				calendar.setTime(CorpdataUtil.getDate(bakeDate));
				calendar.add(calendar.DATE, -1);
				record.setStartDate(CorpdataUtil.getDate(topDate));
				record.setEndDate(CorpdataUtil.getDate(sdf.format(calendar.getTime())));
				if(set != null){
					if(set.getType().equals("0")){
						record.setReceivableDate(CorpdataUtil.getDateFromNow(CorpdataUtil.getDate(topDate),0, -1));
					}else{
						record.setReceivableDate(CorpdataUtil.getDateFromNow(CorpdataUtil.getDate(topDate),1, -set.getDuration()));
					}
				}else{
					record.setReceivableDate(CorpdataUtil.getDate(topDate));
				}
				//record.setReceivableDate(CorpdataUtil.getDate(sdf.format(calendar.getTime())));
				record.setFkDicReceivableType("0");//应收类型
				BigDecimal b1 = new BigDecimal(Double.toString(number));   
				record.setReceivableAmount(b1.multiply(monthRent));
				record.setFlag(0);
				result=super.save(record);
				topDate=bakeDate;
			}else{
				
				int month=CorpdataUtil.dayCompare(CorpdataUtil.getDate(topDate),endDate, 2);
				int day=CorpdataUtil.dayCompare(CorpdataUtil.getDate(CorpdataUtil.addMonth(topDate,month)),endDate, 3)+1;
				
				ContractReceivable record=new ContractReceivable();
				//record.setReceivableNumber(CorpdataUtil.newGuid());
				record.setContract(contractInfo);
				record.setId(CorpdataUtil.getUUID());
				record.setCreater(UserUtil.getCurrentUserid());
				record.setCreated(date);
				record.setState(0);
				record.setModified(date);
				record.setStartDate(CorpdataUtil.getDate(topDate));
				record.setEndDate(endDate);
				//record.setReceivableDate(endDate);
				if(set != null){
					if(set.getType().equals("0")){
						record.setReceivableDate(CorpdataUtil.getDateFromNow(CorpdataUtil.getDate(topDate),0, -1));
					}else{
						record.setReceivableDate(CorpdataUtil.getDateFromNow(CorpdataUtil.getDate(topDate),1, -set.getDuration()));
					}
				}else{
					record.setReceivableDate(CorpdataUtil.getDate(topDate));
				}
				record.setMonthRent(monthRent);
				record.setFlag(0);
				BigDecimal b1 = new BigDecimal(Double.toString(month));   
				BigDecimal b2 = new BigDecimal(Double.toString(day));  
				record.setReceivableAmount(b1.multiply(monthRent));
				record.setFkDicReceivableType("0");//应收类型
				result=super.save(record);
				
				break;
			}
		}
		return result;
		
	}
	
	public Result deleteAllById(String id){
		if(contractReceivableMapper.deleteAllById(id)>0){
    		return ResultUtil.success();
    	}else{
    		return ResultUtil.fail();
    	}
	}
	//删除合同账单
	@Override
	public Result delContractBill(String contractId) {
		// TODO Auto-generated method stub
		if(contractReceivableMapper.delContractBill(contractId)>0){
    		return ResultUtil.success();
    	}else{
    		return ResultUtil.fail();
    	}
	}
	//收款
	@Override
	public Result shoukuanById(String id) {
		ContractReceivable receivable = contractReceivableMapper.selectById(id);
		receivable.setState(1);
		receivable.setPaymentDate(new Date());
		return super.update(receivable);
	}
	//退押金
	@Override
	public int returnYajin(String renewid) {
		return contractReceivableMapper.returnYajin(renewid);
		
	}
/**
 * 
 * @param billType 如果0：查询有账单编号的数据；1：查询无账单编号的；其它数值不考虑账号编号
 * @param date
 * @param state
 * @param teamId
 * @param contractId
 * @param type
 * @param startdate
 * @param enddate
 * @return
 */
	@Override
	public List<ContractReceivable> selectAll(int billType,Date date,String state,String teamId,String contractId,String type,String startdate,String enddate,String yuqi) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Map<String, Object> params = new HashMap<String,Object>();
		params.put("teamId", teamId);
		if(billType == 0){
			params.put("bill", 1);
		}else if(billType == 1){
			params.put("billnum", 1);
		}
		if(date != null){
			params.put("now", sdf.format(date));
		}
		params.put("yuqi", yuqi);
		params.put("state", state);
		params.put("contractId", contractId);
		params.put("type", type);
		params.put("enddate", enddate);
		params.put("startdate", startdate);
		
		return contractReceivableMapper.selectAll(params);
	}
	/**
	 * 获取需要生成账单的应收列表，生成账单
	 */
	@Override
	public void generatingBill() {
		//获取财务设置的生成账单日期
		FinancialSetting set = setServ.findByStatus("1");
		if(set != null){
			List<ContractReceivable> list = selectAll(1, CorpdataUtil.getDateFromNow(new Date(), 1, -set.getDuration()), "0", null, null, null, null, null,null);
			for(ContractReceivable re:list){
				re.setReceivableNumber(System.currentTimeMillis()+"");
				contractReceivableMapper.update(re);
			}
		}
	}
	//发送账单通知
	@Override
	public Result sendBillMessage() {
		Result result = null;
		List<SysMessage> msgList = new ArrayList<SysMessage>();
		List<SysMessageUser> muList = new ArrayList<SysMessageUser>();
		//获取财务设置的发送账单日期
		FinancialSetting set = setServ.findByStatus("2");
		if(set != null){
			List<ContractReceivable> list = selectAll(0, CorpdataUtil.getDateFromNow(new Date(), 1, -set.getDuration()), "0", null, null, null, null, null,null);
			for(ContractReceivable re:list){
				msgServ.initList(re, 1, msgList, muList,0);
			}
		}
		if(msgList.size() > 0){
			result = msgServ.insertList(msgList,muList);
		}
		return result;
	}
	//发送催款通知
	@Override
	public Result sendPromptMessage() {
		Result result = null;
		List<SysMessage> msgList = new ArrayList<SysMessage>();
		List<SysMessageUser> muList = new ArrayList<SysMessageUser>();
		//获取财务设置的发送账单日期
		FinancialSetting set = setServ.findByStatus("2");
		if(set != null){
			List<ContractReceivable> list = selectAll(-1, null, "0",  null, null, null, null, null,set.getDuration()+"");
			for(ContractReceivable re:list){
				msgServ.initList(re, 1, msgList, muList,1);
			}
		}
		if(msgList.size() > 0){
			result = msgServ.insertList(msgList,muList);
		}
		return result;
	}

	@Override
	public void delTemporaryReceive() {
		//删除临时数据
		contractReceivableMapper.delTemporaryReceive();
	}
}
